import { Revenuedata } from "../../../request/zwyApi";
import React, { useEffect, useRef } from "react";
import * as echarts from "echarts";
import { Table } from "antd";
import moduleCss from "../../../styles/RevenueData.module.css";

function RevenueData() {
  const chartRef = useRef(null);
  const pieChartRef = useRef(null);
  const myChart = useRef(null);
  const pieChart = useRef(null);

  const [tableData, setTableData] = React.useState([]);

  useEffect(() => {
    // 初始化柱状图
    myChart.current = echarts.init(chartRef.current);

    // 初始化玫瑰图
    pieChart.current = echarts.init(pieChartRef.current);

    // 从接口获取数据
    Revenuedata().then((res) => {
      if (res.code === 1) {
        const tableDataFromAPI = res.data.table;
        setTableData(tableDataFromAPI);

        const weightChartData = res.data.weightChart.data;
        const departmentChartData = res.data.departmentChart.otherData;

        // 转换数据为 ECharts 需要的格式
        const categories = weightChartData.map((item) => item.product);
        const seriesData = {
          内科综合: weightChartData.map((item) => item["内科综合"]),
          外科综合: weightChartData.map((item) => item["外科综合"]),
          超声科: weightChartData.map((item) => item["超声科"]),
        };

        // 柱状图配置
        const barOption = {
          tooltip: {
            trigger: "axis",
            axisPointer: { type: "shadow" },
          },
          legend: {
            itemHeight: 10,
            itemWidth: 16,
            data: ["内科综合", "外科综合", "超声科"],
            textStyle: {
              fontSize: 10, // 设置图例字体大小
            },
          },
          xAxis: {
            type: "value",
          },
          yAxis: {
            type: "category",
            data: categories,
            inverse: true, // 将 y 轴反转以实现横向布局
          },
          series: [
            {
              name: "内科综合",
              type: "bar",
              stack: "总量",
              data: seriesData["内科综合"],
            },
            {
              name: "外科综合",
              type: "bar",
              stack: "总量",
              data: seriesData["外科综合"],
            },
            {
              name: "超声科",
              type: "bar",
              stack: "总量",
              data: seriesData["超声科"],
            },
          ],
        };

        // 设置柱状图配置项和数据
        myChart.current.setOption(barOption);

        // 玫瑰图配置
        const pieOption = {
          legend: {
            itemHeight: 10,
            itemWidth: 16,
            orient: "horizontal",
            x: "center",
            y: "top",
            data: departmentChartData.map((item) => item.name),
            textStyle: {
              fontSize: 10, // 设置图例字体大小
            },
          },
          toolbox: {
            show: false,
          },
          series: [
            {
              name: "Nightingale Chart",
              type: "pie",
              radius: ["10%", "130"],
              center: ["50%", "50%"],
              roseType: "area",
              itemStyle: {
                borderRadius: 8,
              },
              label: {
                formatter: "{b}: {c} ({d}%)",
                position: "outside",
                distance: 40,
                avoidLabelOverlap: true, // 避免标签重叠
              },
              data: departmentChartData,
              padding: [20, 0, 20, 0],
            },
          ],
          grid: {
            top: "50%", // 为图表主体提供上边距
          },
        };

        // 设置玫瑰图配置项和数据
        pieChart.current.setOption(pieOption);

        // 监听窗口大小变化，自适应图表大小
        window.addEventListener("resize", () => {
          myChart.current.resize();
          pieChart.current.resize();
        });

        // 组件卸载时销毁图表
        return () => {
          window.removeEventListener("resize", () => {
            myChart.current.resize();
            pieChart.current.resize();
          });
          if (myChart.current) {
            myChart.current.dispose();
          }
          if (pieChart.current) {
            pieChart.current.dispose();
          }
        };
      } else {
        console.error("接口请求失败:", res.msg);
      }
    });
  }, []);

  const columns = [
    {
      title: "住院部",
      dataIndex: "name",
      key: "name",
      width: "250px",
    },
    {
      title: "本周服务医务数",
      dataIndex: "server",
      key: "server",
      width: "250px",
    },
    {
      title: "金额",
      dataIndex: "money",
      key: "money",
      width: "250px",
    },
    {
      title: "上周金额",
      dataIndex: "lastweek",
      key: "lastweek",
      width: "250px",
    },
    {
      title: "本月金额",
      dataIndex: "month",
      key: "month",
      width: "250px",
    },
    {
      title: "审计人员",
      dataIndex: "audit",
      key: "audit",
      width: "250px",
    },
    {
      title: "负责人",
      dataIndex: "chargeperson",
      key: "chargeperson",
      width: "250px",
    },
  ];

  return (
    <div style={{ display: "flex", flexWrap: "wrap" }}>
      <div ref={chartRef} style={{ width: "50%", height: "350px" }}></div>
      <div ref={pieChartRef} style={{ width: "50%", height: "350px" }}></div>

      <div>
        <div
          style={{ fontSize: "20px", paddingLeft: "10px" }}
          className={moduleCss.fontSize}
        >
          详情数据
        </div>
        <Table
          columns={columns}
          dataSource={tableData}
          pagination={false}
          rowKey="id"
          style={{ width: "100%", paddingLeft: "10px" }}
          className={moduleCss.hig}
        />
      </div>
    </div>
  );
}

export default RevenueData;
